/*!
 * cadastro.js
 * @project MB Consultoria Jurídica
 * @developer Thiago Braga <thibraga06@gmail.com>
 * @designer Ana Lau <contato@analau.com.br>
 * @url www.mbconsultoriajuridica.com.br
 */


var valid = true,
  nome = $('#nome'),
  email = $('#email')
  salvar = $('#salvar'),
  grupo = $('#grupo'),
  modal_password = $('#modal-password');


/**
 * @function checkPassword
 * @description Compare two password fields.
 * @return {Boolean}
 */
var checkPassword = (function () {
  var repeat = $('#repeat'),
    senha = $('#senha');
  if (senha.val() == "" || repeat.val() == "" || senha.val() !== repeat.val()) {
    senha.parents('.control-group').addClass('error');
    repeat.parents('.control-group').addClass('error');
    valid = false;
  } else {
    senha.parents('.control-group').removeClass('error');
    repeat.parents('.control-group').removeClass('error');
    valid = true;
  }
  return valid;
});


/**
 *
 */
var modalPassword = (function () {
  var div_modal = $('#div-modal'),
    modal_header = $('#result-header'),
    modal_body = $('#result-body'),
    modal_footer = $('#result-footer');
  modal_header.html('Alterar senha');
  modal_body.html('\n\
    <p>Utilize letras, números e caracteres especiais para tornar sua senha mais segura. Redigite sua senha no campo abaixo para verificação.</p>\n\
    <form id="new-user" class="form-cadastro form-horizontal">\n\
      <fieldset>\n\
        <div class="control-group">\n\
          <label class="control-label" for="senha">Nova senha</label>\n\
          <div class="controls">\n\
            <input id="senha" name="senha" class="input-medium passwordTarget" type="password" required />\n\
            <label class="help-inline" name="passwordStrengthLabel" id="passwordStrengthLabel" />\n\
          </div>\n\
        </div>\n\
        <div class="control-group">\n\
          <label class="control-label" for="repeat">Repita a senha</label>\n\
          <div class="controls">\n\
            <input id="repeat" class="input-medium" type="password" required />\n\
          </div>\n\
        </div>\n\
      </fieldset>\n\
    </form>');
  modal_footer.html('<button id="save-modal" class="btn btn-inverse">Alterar</button>\n\
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancelar</button>');
  div_modal.modal('show');
});


/**
 * @function checkCpf
 * @description Check the CPF via ajax. Overwrite the checkCpf app function.
 */
var checkCpf = (function () {
  if (cpf.val().replace(/[^\d]+/g, '') != '') {
    var data = { cpf: cpf.val().replace(/[^\d]+/g, '') };
    if (validateCpf(data.cpf)) {
      $.post(base_url('usuarios/ajax_cpf'), data, function (response) {
        if (!response.success) {
          noty({ text: response.message });
          cpf.val('').focus();
        }
      }, 'json');
    } else {
      noty({ text: 'CPF inválido.' });
      cpf.val('').focus();
    }
  }
});


/**
 * @function saveForm
 * @description Save the form via ajax.
 */
var saveForm = (function () {
  var senha = $('#senha');
  if (valid && validateCpf(cpf.val())) {
    var data = {
      cpf: cpf.val().replace(/[^\d]+/g, ''),
      nome: nome.val(),
      email: email.val(),
      senha: senha.val()
    };
    $.post(base_url('usuarios/ajax_save'), data, function (response) {
      noty({ text: response.message, type: response.type });
      if (!response.success)
        $('#' + response.field).focus();
    }, 'json');
  } else {
    noty({ text: 'Preencha os campos corretamente.', type: 'warning' });
  }
});


/**
 * @function showInput
 * @description
 */
var showInput = (function () {
  var fieldset = $('#advogado');
  grupo.val() == "3" ? fieldset.show(300) : fieldset.hide(300);
});


/* Events */
salvar.on('click', function () {
  saveForm();
});

$(document).on('keyup', '#senha', function () {
  checkPassword();
});

$(document).on('keyup', '#repeat', function () {
  checkPassword();
});

modal_password.on('click', function () {
  modalPassword();
});

grupo.on('change', function () {
  showInput();
});